package com.act;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabWidget;
import android.widget.TextView;

import com.control.UserControl;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.fragment.FirstFragment;
import com.fragment.MessageFragment;
import com.fragment.MineFragment;
import com.fragment.ServiceFragment;
import com.mUI.MyDialog;
import com.umeng.analytics.MobclickAgent;
import com.xike.kyt.R;
import com.xike.util.MLog;
import com.xike.util.Manager;
import com.xike.util.StringUtil;

public class MainAct extends FragmentActivity {

	public static final int REQUEST_CODE_TO_LOGIN = 1;

	final int[] tabitemImg = new int[] { R.drawable.tab_first_selector, R.drawable.tab_service_selector, R.drawable.tab_message_selector, R.drawable.tab_mine_selector };
	final int[] tabitemText = new int[] { R.string.tab_first, R.string.tab_service, R.string.tab_message, R.string.tab_mine };

	private TabHost tabHost;
	private Fragment currentFragment;
	TextView tv_msgUnReadNum;
	NewMessageBroadcastReceiver msgReceiver;
	String currentFragmentTag;
	String toShowFragmentTag;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_main);

		if (savedInstanceState != null && savedInstanceState.containsKey("currentShowFragmenTag")) {
			currentFragmentTag = savedInstanceState.getString("currentShowFragmenTag");
		} else {
			currentFragmentTag = getString(tabitemText[0]);
		}

		initViews();
		checkChat();

	}

	@Override
	protected void onResume() {
		super.onResume();
		updateUnreadLabel();
		EMChatManager.getInstance().activityResumed();
		MobclickAgent.onResume(this); // 统计时长
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TO_LOGIN) {
			if (resultCode > 0) {
				tabHost.setCurrentTabByTag(toShowFragmentTag);
				showFragment(toShowFragmentTag);
				checkChat();
			} else {
				tabHost.setCurrentTabByTag(currentFragmentTag);
			}

		} else {
			// 来自Fragment的intent
			if (currentFragment != null) {
				currentFragment.onActivityResult(requestCode, resultCode, data);
				if (resultCode > 0) { // 登录成功的情况下，要初始化环信
					checkChat();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void initViews() {
		tabHost = (TabHost) findViewById(R.id.tabhost);
		tabHost.setup();
		for (int i = 0; i < 4; i++) {
			LinearLayout itemLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_tabitem, null, false);
			TextView tab_tv = (TextView) itemLayout.findViewById(R.id.tabTv);
			ImageView tab_img = (ImageView) itemLayout.findViewById(R.id.tabImage);
			tab_tv.setText(getString(tabitemText[i]));
			tab_img.setBackgroundResource(tabitemImg[i]);
			TabHost.TabSpec tSpecHome = tabHost.newTabSpec(getString(tabitemText[i]));
			tSpecHome.setIndicator(itemLayout);
			tSpecHome.setContent(new MyTabContent(getBaseContext()));
			tabHost.addTab(tSpecHome);
		}
		TabWidget tabWidget = tabHost.getTabWidget();
		for (int i = 0; i < tabWidget.getChildCount(); i++) {
			tabWidget.getChildAt(i).getLayoutParams().height = (int) getResources().getDimension(R.dimen.height_tab);
		}

		tv_msgUnReadNum = (TextView) tabHost.getTabWidget().getChildAt(2).findViewById(R.id.tab_tv_unReadNUM);
		tabHost.setup();
		tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				toShowFragmentTag = tabId;
				if (!UserControl.isLogined() && !tabId.equals(getString(tabitemText[0])) && !tabId.equals(getString(tabitemText[1]))) {
					Intent it_login = new Intent(MainAct.this, LoginAct.class);
					startActivityForResult(it_login, REQUEST_CODE_TO_LOGIN);
				} else {
					currentFragmentTag = tabId;
					showFragment(tabId);
				}

			}
		});

		tabHost.setCurrentTabByTag(currentFragmentTag);
		showFragment(currentFragmentTag);

	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			msgReceiver = new NewMessageBroadcastReceiver();
			IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
			intentFilter.setPriority(3);
			registerReceiver(msgReceiver, intentFilter);
			EMChat.getInstance().setAppInited();

			updateUnreadLabel();

		}

	};

	private void showFragment(String tag) {

		Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.setTransitionStyle(FragmentTransaction.TRANSIT_ENTER_MASK);
		if (currentFragment != null && !tag.equals(currentFragment.getTag())) {
			ft.hide(currentFragment);
		}
		if (fragment == null) {
			if (tag.equals(getString(R.string.tab_first))) {
				fragment = new FirstFragment();
			} else if (tag.equals(getString(R.string.tab_service))) {
				fragment = new ServiceFragment();
			} else if (tag.equals(getString(R.string.tab_message))) {
				fragment = new MessageFragment();
			} else if (tag.equals(getString(R.string.tab_mine))) {
				fragment = new MineFragment();
			}
			ft.add(R.id.realtabcontent, fragment, tag);
			ft.commitAllowingStateLoss();
		} else {
			ft.show(fragment);
			ft.commitAllowingStateLoss();
		}
		currentFragment = fragment;
	}

	private class MyTabContent implements TabContentFactory {
		private Context mContext;

		public MyTabContent(Context context) {
			mContext = context;
		}

		@Override
		public View createTabContent(String tag) {
			View v = new View(mContext);
			return v;
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			final MyDialog dialog = new MyDialog(this);
			dialog.show();
			dialog.setTitle("确定退出？");
			dialog.setOnBtnLeftClickListener("确定", new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.cancel();
					finish();
					Manager.getInstance(getApplicationContext()).shutDown();
				}
			});
			dialog.setOnBtnRightClickListener("取消", new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.cancel();
				}
			});
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 注销广播接收者
		try {
			unregisterReceiver(msgReceiver);
		} catch (Exception e) {
		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString("currentShowFragmenTag", currentFragmentTag);
		super.onSaveInstanceState(outState);
	}

	private void checkChat() {

		if (!EMChatManager.getInstance().isConnected() && StringUtil.isNotNull(UserControl.getImUserName()) && StringUtil.isNotNull(UserControl.getImPwd())) {
			Manager.singleThread.execute(new Runnable() {

				@Override
				public void run() {

					EMChatManager.getInstance().login(UserControl.getImUserName(), UserControl.getImPwd(), new EMCallBack() {

						@Override
						public void onSuccess() {
							MLog.e("MainAct", "Login EMChat success!");
							MyApplication.getInstance().setUserName(UserControl.getImUserName());
							MyApplication.getInstance().setPassword(UserControl.getImPwd());

							handler.sendEmptyMessage(0);
						}

						@Override
						public void onProgress(int arg0, String arg1) {
						}

						@Override
						public void onError(int arg0, String arg1) {
							MLog.e("MainAct", "Login EMChat onError!" + arg1);
						}
					});
				}

			});
		} else {
			handler.sendEmptyMessage(0);
		}
	}

	/**
	 * 消息广播接收者
	 * 
	 */
	private class NewMessageBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			updateUnreadLabel();
			if (currentFragmentTag.equals(getString(R.string.tab_message))) {
				// 当前页面如果消息页面，刷新此页面
				if (currentFragment != null) {
					((MessageFragment) currentFragment).refresh();
				}
			}
			// 记得把广播给终结掉
			abortBroadcast();
		}
	}

	/**
	 * 消息回执BroadcastReceiver
	 */
	private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String msgid = intent.getStringExtra("msgid");
			String from = intent.getStringExtra("from");
			EMConversation conversation = EMChatManager.getInstance().getConversation(from);
			if (conversation != null) {
				// 把message设为已读
				EMMessage msg = conversation.getMessage(msgid);
				if (msg != null) {
					msg.isAcked = true;
				}
			}
			abortBroadcast();
		}
	};

	/**
	 * 刷新未读消息数
	 */
	public void updateUnreadLabel() {
		int count = getUnreadMsgCountTotal();
		if (count > 0) {
			tv_msgUnReadNum.setText(String.valueOf(count));
			tv_msgUnReadNum.setVisibility(View.VISIBLE);
		} else {
			tv_msgUnReadNum.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 获取未读消息数
	 * 
	 * @return
	 */
	public int getUnreadMsgCountTotal() {
		int unreadMsgCountTotal = 0;
		unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
		return unreadMsgCountTotal;
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
}
